package com.jf.cloud.product.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.jf.cloud.product.service.StockBillLogItemService;
import com.jf.cloud.product.service.TakeStockSpuService;
import com.jf.cloud.product.vo.StockBillLogItemImportExcelVO;
import com.jf.cloud.product.vo.StockBillLogItemImportVO;
import com.jf.cloud.product.vo.TakeStockSpuExcelVO;
import com.jf.cloud.product.vo.TakeStockSpuImportVO;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TakeStockSpuExcelListener extends AnalysisEventListener<TakeStockSpuExcelVO> {

    private TakeStockSpuService takeStockSpuService;
    //错误信息集合
    private List<String> errorList ;
    private List<TakeStockSpuExcelVO> list;
    private TakeStockSpuImportVO takeStockSpuImportVO;
    private Long takeStockId;

    /**
     * 每隔1000条数据存储数据库，然后清理map ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;

    public TakeStockSpuExcelListener() {}

    public TakeStockSpuExcelListener(TakeStockSpuService takeStockSpuService, List<String> errorList, Long takeStockId, TakeStockSpuImportVO takeStockSpuImportVO) {
        this.takeStockSpuService = takeStockSpuService;
        this.errorList = new ArrayList<>();
        this.list = new ArrayList<>(BATCH_COUNT);
        this.takeStockSpuImportVO = takeStockSpuImportVO;
        this.takeStockId = takeStockId;
    }

    /**
     * 这个每一条数据解析都会来调用
     */
    @Override
    public void invoke(TakeStockSpuExcelVO takeStockSpuExcelVO, AnalysisContext analysisContext) {
        if (Objects.isNull(takeStockSpuExcelVO)) {
            return;
        }
        if(list.size() >= BATCH_COUNT){
            saveData();
        }
        list.add(takeStockSpuExcelVO);
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        takeStockSpuService.importExcel(list, errorList, takeStockId, takeStockSpuImportVO);
        list.clear();
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //确保所有数据都能入库
        saveData();
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        int row=0,column=0;
        if (exception instanceof ExcelDataConvertException){
            ExcelDataConvertException convertException=(ExcelDataConvertException) exception;
            row=convertException.getRowIndex() + 1;
            column=convertException.getColumnIndex() + 1;
            errorList.add("  第"+row+"行，第 "+column+"列数据不符合要求，请检验后重新导入!");
        }
    }
}
